package com.cyy.dyeing.controller;

import com.cyy.dyeing.common.CurrentUser;
import com.cyy.dyeing.common.Result;
import com.cyy.dyeing.common.TokenUtils;
import com.cyy.dyeing.dto.LoginDto;
import com.cyy.dyeing.exception.BusinessException;
import com.cyy.dyeing.model.User;
import com.cyy.dyeing.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: cyy
 * @Date: 2024/7/22
 * 登录功能
 */
@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private UserService userService;

    /**
     * 登录功能
     * @param loginDto
     * @return
     */
    @PostMapping
    public Result userLogin(@RequestBody LoginDto loginDto){
        User user = userService.getUserById(loginDto.getU_id());
        if(user == null){
            throw new BusinessException("该用户不存在");
        }else{
            if(!user.getU_pwd().equals(loginDto.getU_pwd())){
                throw new BusinessException("密码不正确");
            }
        }
        //调用登录业务 返回CurrentUser
        CurrentUser currentUser = userService.findUser(loginDto);
        //登录逻辑
        String token = TokenUtils.loginSign(currentUser, loginDto.getU_pwd());
        //向客户端发送token
        return Result.ok(token);
    }
}
